package org.davidliebman.android.flyer;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import android.app.ActivityManager;
import android.app.Dialog;
import android.app.ListActivity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.*;
import android.content.*;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.sqlite.SQLiteDatabase;

import android.util.Log;
//import android.text.InputType;
//import android.util.Log;
import android.view.View.OnKeyListener;
import java.util.ArrayList;


import android.view.*;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.app.AlertDialog;

import com.actionbarsherlock.app.SherlockListFragment;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

//import android.util.Log;


public class FragmentPlayers extends SherlockListFragment {
		
    public static final String AWESOME_NAME = new String("org.awesomeflyer");
    public static final String SAVED_NUM_SCORES = new String("saved_num_scores");
	public static final String SAVED_ROOM_NUM = new String("room");
	public static final String SAVED_LOOK_FOR_XML = new String("look_for_xml");
	public static final String SAVED_REMEMBER_PLAYER = new String("remember_player");
	public static final String SAVED_ANALYTICS = new String("analytics_tracking");
	public static final String SAVED_TOS = new String("terms_of_service_shown");
	public static final String SAVED_VERSIONCODE = new String("old_versioncode");
	
    private ArrayList<Record> mNames = new ArrayList<Record>();
    private Record mRec = new Record();
    private SharedPreferences mPreferences;
    //private Button mGoButton;
    private EditText mEdittext;
    private RecordAdapter mAdapter;
    //private SplashScreen mSplash;
    private Animation myFadeInAnimation;
    private TextView mPlayerText;
    private TextView mNumPlayers;
    private int mPreferredNumRecords;
    private int mRoomNumSelected = 1;
    private boolean mLookForXml;
    private boolean mIsNewRecord = false;
    private boolean mShowMenu = false;
    
    public static final int VIEW_SPLASH = 0;
    public static final int VIEW_PLAYERS = 1;
    public static final int VIEW_TEXT = 2;
    public static final int VIEW_SCORES = 3;
    
    public static final int TEXT_NOTEXT = -1;
    public static final int TEXT_HELP = 0;
    public static final int TEXT_STORY = 1;
    public static final int TEXT_LEGAL = 2;
    
    public static final int DIALOG_USERNUM_CHANGED = 0;
    public static final int DIALOG_STARTGAME = 1;
    public static final int DIALOG_UNUSED = 2;
    
//    public static final int MENU_BASE = Menu.FIRST;
//    public static final int MENU_GROUP_SUBMENU = MENU_BASE + 1;
//    public static final int MENU_GROUP_ROOMS = MENU_BASE + 2; //this is always last entry

    
    protected boolean mActive = true;
    private boolean mRememberPlayer = true;
    private boolean mGoogleAnalytics;
    private boolean mTermsOfService;
    private int mVersionCode = 1;
    public static final String UA_NUMBER = new String("UA-19479622-6");
    public GoogleAnalyticsTracker tracker;
    private Record mHighScores;
    private Scores.ScoreOpenHelper mScoresHelper;
    private Scores mScores;
    private SQLiteDatabase db;
    
	private InitBackground.LevelList mList;
	private InitBackground.ParseXML mParser = new InitBackground.ParseXML(this.getActivity());
	private ParseChallengeXML mChallengeParser = new ParseChallengeXML(this.getActivity());

	public FragmentPlayers() {
		
	}
	
	public FragmentPlayers(Record mHighS) {
		this.mHighScores = mHighS;
	}

	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAdapter = new RecordAdapter(this.getActivity(), R.layout.fragment_screen_slide_players, mNames);
        mAdapter.setNotifyOnChange(true);
        mAdapter.notifyDataSetChanged();
        mScores = new Scores(this.getActivity(), mHighScores);

        //this.getActivity().setContentView(R.layout.players);      
        setListAdapter(mAdapter);
        
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener () {
        	
        	@Override
        	 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		mRec = mNames.get(position);

        		//AlertNumRecords mAlert = new AlertNumRecords(Players.this,mHighScores,mRec);
        		mPreferredNumRecords = mHighScores.getNumRecords();
        		if ( mPreferredNumRecords != mRec.getNumRecords() ) {
      			   //showDialog(Players.DIALOG_USERNUM_CHANGED);
        		}
        		
        		//mRec.setNumRecords(mAlert.alertUser()); // TODO: is this redundant??
        		mHighScores = mRec;

        		Toast.makeText(getActivity(), "Player Selected: " + mHighScores.getName(), Toast.LENGTH_SHORT).show();
        		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());//getActivity().getSharedPreferences(AWESOME_NAME, getActivity().MODE_PRIVATE);
            	mHighScores.setNewRecord(false);
        		//mHighScores.addToPreferences(preferences);
        		mScores.insertPrefs(mHighScores);
                mPlayerText.setText("Player Chosen: " +mHighScores.getName());
                ((TextView)getView().findViewById(R.id.edittext_name)).setText("");
                /* save num of high scores */
                SharedPreferences.Editor mSave = preferences.edit();
                mSave.putInt(Pager.SAVED_NUM_SCORES, mHighScores.getNumRecords());
                mSave.commit();
                mNumPlayers.setText("This is where you enter a new player name, or choose from a list of " + mHighScores.getNumRecords() + " players.");
                
                /* save num of high scores for player */
                //TODO: TEST ME!!
                mScores.updateNumOfRecords(mHighScores.getNumRecords());
                
                /* adjust number of high scores shown */
                mScores.pruneScoresList();
                
                mIsNewRecord = false;
        	 }
        	
        	
        	
        });
        
        /* long click code */
        lv.setLongClickable(true);
        lv.setOnItemLongClickListener(new OnItemLongClickListener () {
        	
        	public boolean onItemLongClick (AdapterView<?> parent, View view, int position, long id) {
//        		Toast.makeText(Players.this, "Player - Num Records: " + mNames.get(position).getNumRecords() + 
//        				" Record ID: " + mNames.get(position).getRecordIdNum(), Toast.LENGTH_LONG).show();

        		final Record mRec = mNames.get(position);
        		//////////////////
        		Dialog  dialog = new Dialog(getActivity());
            	AlertDialog.Builder builder;
            	AlertDialog alertDialog;
            	LayoutInflater mInflater = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
            	View mLayout;
            	
            	mLayout = mInflater.inflate(R.layout.congrats, 
            			(ViewGroup) getActivity().findViewById(R.id.layout_root));
            	mLayout.findViewById(R.id.image).setBackgroundResource(R.drawable.ic_launcher);
            	
            	
            		
         		   if ( true ) {
        	   	    	builder = new AlertDialog.Builder(getActivity());
        	   	    	builder.setView(mLayout);
        	   	    	String mAMessage = new String("Do you really want to delete this record?? " + 
        	   	    			mRec.getName() + " will be gone forever. ");
        	   	    	((TextView)mLayout.findViewById(R.id.congrats_text)).setText(mAMessage);
        	   	    	String mPositive = new String("Delete " + mRec.getName() );
        	   	    	String mNegative = new String("Skip " + mRec.getName() );
        	   	    	builder.setCancelable(false)
        	   	    	       .setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
        	   	    	           public void onClick(DialogInterface dialog, int id) {
        	   	    	        	   //adjustPlayersList(mHighScores.getNumRecords());
        	   	    	        	   mScores.deletePlayerRecord(mRec.getRecordIdNum());
        	   	    	        	   
        	   	    	        	mNames = mScores.getHighScorePlayerList(mHighScores.getNumRecords());
        	                        
        	                        mAdapter = new RecordAdapter(getActivity(), R.layout.fragment_screen_slide_players, mNames);
        	                        setListAdapter(mAdapter);
        	                    	mAdapter.notifyDataSetChanged();
        	   	    	        	   
        	   	    	        	   
        	   	    	        	   dialog.cancel();
        	   	    	        	   //removeDialog(Pager.DIALOG_USERNUM_CHANGED);
        	   	    	           }
        	   	    	       })
        	   	    	       .setNegativeButton(mNegative, new DialogInterface.OnClickListener() {
        	   	    	           public void onClick(DialogInterface dialog, int id) {
        	   	    	        	   mHighScores.setNumRecords(mHighScores.getNumRecords());	
        	   	    	        	   //removeDialog(Players.DIALOG_USERNUM_CHANGED);
        	   	    	                dialog.cancel();
        	   	    	           }
        	   	    	       });
        	   	    	AlertDialog alert = builder.create();
        	   	    	dialog = (Dialog) alert;
        	   	    	dialog.show();
         		   }
        		//////////////////
        		
        		
        		return true;
        	}
        });
        
        mEdittext = (EditText) getActivity().findViewById(R.id.edittext_name);
        
        mEdittext.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
            	mIsNewRecord = true;
            	Log.e("Players", "isNewRecord");
            	
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                  // Perform action on key press
                	mIsNewRecord = true;
                	if ( ! mEdittext.getText().toString().contentEquals("") &&
                			! mEdittext.getText().toString().contentEquals((new Record()).getName())) {
                		setNewName();
                		mNames = mScores.getHighScorePlayerList(mHighScores.getNumRecords());
                        
                        mAdapter = new RecordAdapter(getActivity(), R.layout.fragment_screen_slide_players, mNames);
                        setListAdapter(mAdapter);
                    	mAdapter.notifyDataSetChanged();
                	}
     
                	return true;
                }

            	
                return false;
                
            }
            
            
        });
        mEdittext.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// 
				if (hasFocus) {
					mIsNewRecord = true;
				}
				
			}
        	
        });
        
      

        
        mNumPlayers = (TextView) getView().findViewById(R.id.text_num_message);
        mNumPlayers.setText("This is where you choose from a list of " + mHighScores.getNumRecords() + " players.");
        
        mPlayerText = (TextView) getView().findViewById(R.id.text_player_name);
        mPlayerText.setText("Player Chosen: " +mHighScores.getName());
        
        mScores.pruneScoresList();
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_screen_slide_players, container, false);
	
        mScores = new Scores(this.getActivity(), mHighScores);
        //////////////////////start SplashScreen
        /* init database if not already done so */
        mScoresHelper = new Scores.ScoreOpenHelper(this.getActivity());
        db = mScoresHelper.getReadableDatabase();
        db.close();
        
        /* one highscores record passed around for preferences */
        mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());//this.getActivity().getSharedPreferences(AWESOME_NAME, this.getActivity().MODE_PRIVATE);
        mRememberPlayer = mPreferences.getBoolean(Pager.SAVED_REMEMBER_PLAYER, true);
        //mHighScores = new Record();

        mHighScores = mScores.getHighScorePrefs();
        /* if 'anonymous' then blank out record. */
        if(mHighScores.getName().contentEquals((new Record()).getName())) {
        	mHighScores = new Record();
        }
        
    
        
        /* retrieve Record mHighScores */
    	//mHighScores = new Record();
        mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); // getActivity().getSharedPreferences(AWESOME_NAME, getActivity().MODE_PRIVATE);
        //mHighScores.getFromPreferences(mPreferences);
        mHighScores = mScores.getHighScorePrefs();
        this.mPreferredNumRecords = mHighScores.getNumRecords();
        
        mScores = new Scores(this.getActivity(), mHighScores);
        
        mNames = mScores.getHighScorePlayerList(mHighScores.getNumRecords());

        


        
        return rootView;
    }
    
    /* when the activity is resumed, re-display a new list */
    @Override
    public void onResume() {
    	super.onResume();
    	
    	//this.showView(VIEW_PLAYERS);
    	
    	/* retrieve Record mHighScores */
    	//mHighScores = new Record();
        mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());//getActivity().getSharedPreferences(AWESOME_NAME, getActivity().MODE_PRIVATE);
        
        mRememberPlayer = mPreferences.getBoolean(Pager.SAVED_REMEMBER_PLAYER, true);
        //mHighScores = new Record();

        if(!mRememberPlayer) {
        	//mHighScores.addToPreferences(mPreferences);
        	mScores.insertPrefs(mHighScores);
        }
        else {
        	//mHighScores.getFromPreferences(mPreferences);
        	mHighScores = mScores.getHighScorePrefs();
        }
        
        //mHighScores.getFromPreferences(mPreferences);
        mPlayerText.setText("Player Chosen: " +mHighScores.getName());
        
        this.mPreferredNumRecords = this.mPreferences.getInt(Pager.SAVED_NUM_SCORES, Record.RADIO_PLAYERS_FIFTY);
        mNumPlayers.setText("This is where you choose from a list of " + this.mPreferredNumRecords + " players.");

        try {
    		mScores.closeAll();
    	}
    	catch (NullPointerException e) {
    		//Log.e("Awesomeguy", "Null Pointer Players");
    	}
        
        mScores = new Scores(this.getActivity(), mHighScores);

    	
    	ArrayList<Record> temp = mScores.getHighScorePlayerList(mHighScores.getNumRecords());
        this.mNames.clear();
        this.mNames.addAll(temp);
        mAdapter = new RecordAdapter(this.getActivity(), R.layout.fragment_screen_slide_players, mNames);
        setListAdapter(mAdapter);
    	mAdapter.notifyDataSetChanged();
    	
    	/////////////////////////////

    	
    }
    
    
    public void setNewName() {
    	 mRec = new Record();
         mRec.setName(mEdittext.getText().toString().trim());
         mRec.setNumRecords(mHighScores.getNumRecords());
         if ( isNameTaken(mNames, mRec.getName()) ) {
             Toast.makeText(getActivity(), "This name is already taken: " + mEdittext.getText(), Toast.LENGTH_LONG).show();

         }
         else {
             Toast.makeText(getActivity(), "Player Selected: " + mEdittext.getText(), Toast.LENGTH_SHORT).show();
       	  	mHighScores = mRec;
       	  	mHighScores.setNewRecord(true);
       	  
       	  	mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
       	  	//mHighScores.addToPreferences(mPreferences);
       	  	mScores.insertPrefs(mHighScores);
       	  	mPlayerText.setText("Player Chosen: " +mHighScores.getName());
             mNumPlayers.setText("This is where you choose from a list of " + mHighScores.getNumRecords() + " players.");
             SharedPreferences.Editor edit = mPreferences.edit();
             edit.putInt(Pager.SAVED_ROOM_NUM, mHighScores.getLevel());
             edit.commit();
             mHighScores = mScores.insertRecord(mHighScores);

         }
        // return true;
    }
    

    
    @Override
	public void onDestroy() {
    	super.onDestroy();
    	//tracker.stop();
    }
    

    
    public void adjustPlayersList(int mNewNumOfRecords) {
    	//mPreferredNumRecords = mHighScores.getNumRecords();
		
		//mPreferredNumRecords = mNewNumOfRecords;
		
		mHighScores.setNumRecords(mNewNumOfRecords);
        /* save num of high scores */
        SharedPreferences.Editor mSave = mPreferences.edit();
        mSave.putInt(Options.SAVED_NUM_SCORES, mNewNumOfRecords);
        mSave.commit();
        mNumPlayers.setText("This is where you enter a new player name, or choose from a list of " + mHighScores.getNumRecords() + " players.");
        
        /* save num of high scores for player */
        
        //save options again...
        //mHighScores.addToPreferences(mPreferences);
        mScores.insertPrefs(mHighScores);
    	mScores.setHighScores(mHighScores);
    	mScores.updateOptions(mHighScores.getRecordIdNum());
    	
    	mScores.pruneScoresList();
    	mNames.clear();
    	mNames.addAll(mScores.getHighScorePlayerList(mNewNumOfRecords));
        mAdapter = new RecordAdapter(getActivity(), R.layout.players, mNames);

        setListAdapter(mAdapter);
    
        mAdapter.notifyDataSetChanged();

    	mPreferredNumRecords = mNewNumOfRecords;
	
    }
    
    
    /* determine if a name is already taken */
    public static boolean isNameTaken(ArrayList<Record> mNames, String test) {
    	boolean value = false;
    	if (mNames.size() > 0) {
    		for (int i = 0; i < mNames.size(); i ++ ) {
    			if (mNames.get(i).getName().contentEquals(test)) {
    				value = true;
    			}
    		}
    	}
    	
    	return value;
    }
    
    @Override
    public void onPause() {
    
//    	if (mSplash != null) {
//    		mSplash.cancel(true);
//    	}
    	
        mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());//getActivity().getSharedPreferences(AWESOME_NAME, getActivity().MODE_PRIVATE);
    	//mHighScores.addToPreferences(mPreferences);
    	mScores.insertPrefs(mHighScores);
    	
    	SharedPreferences.Editor edit = mPreferences.edit();
        edit.putBoolean(SAVED_REMEMBER_PLAYER, mRememberPlayer);
        edit.commit();
    	try {
    		mScores.closeAll();
    	}
    	catch(NullPointerException e) {
    		//Log.e("Awesomeguy", "Null Pointer Players");
    	}
    	super.onPause();
    }
    
    
    /* special adapter for displaying list from ArrayList */
    public class RecordAdapter extends ArrayAdapter<Record> {
    	ArrayList<Record> mList;
    	Context mContext;
    	int mPosition;
    	
    	public RecordAdapter(Context context, int resourceID, ArrayList<Record> list) {
            super(context, resourceID, list);
            this.mList = list;
            mContext = context;
    	}
    	
    	
    	@Override
        public View getView(int position, View convertView, ViewGroup parent) {
    		
    		LayoutInflater inflater = (LayoutInflater)mContext.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
    		convertView = inflater.inflate(R.layout.data_players_row, null);
    		Record mRec = mList.get(position);
    		mPosition = position;
    		
    		TextView mName = (TextView) convertView.findViewById(R.id.text_name);
    		TextView mScore = (TextView) convertView.findViewById(R.id.text_score);
//    		TextView mLevel = (TextView) convertView.findViewById(R.id.text_level);
    		ImageView mImage = (ImageView) convertView.findViewById(R.id.icon);
    		
    		mName.setText( mRec.getName() );//+ " id " + mRec.getRecordIdNum());
    		//mName.setTextSize(20);
    		mScore.setText("Personal Best Score: "+ mRec.getScore());
//    		mLevel.setText("Last Checkpoint: Level " + mRec.getLevel());
    		mImage.setImageResource(this.getGuyIcon(position));
    		
    		
    		return convertView;
    	}
    	
    	public int getGuyIcon(int mPosition ) {
    		int mI = R.drawable.guy_icon;
    		switch(mPosition % 9) {
    		case 0:
    			mI = R.drawable.ic_guy_0;
    			break;
    		case 1:
    			mI = R.drawable.ic_guy_1;
    			break;
    		case 2:
    			mI = R.drawable.ic_guy_2;
    			break;
    		case 3:
    			mI = R.drawable.ic_guy_3;
    			break;
    		case 4:
    			mI = R.drawable.ic_guy_4;
    			break;
    		case 5:
    			mI = R.drawable.ic_guy_5;
    			break;
    		case 6:
    			mI = R.drawable.ic_guy_6;
    			break;
    		case 7:
    			mI = R.drawable.ic_guy_7;
    			break;
    		case 8:
    			mI = R.drawable.ic_guy_8;
    			break;
    		}
    		
    		return mI;
    	}
    	
    };
    
    
    
}


